package com.hzit.user.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServletServerHttpAsyncRequestControl;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Configuration
public class MyRequestInterceptor implements RequestInterceptor {

	/**
	 *
	 * @param template openfeign为我们创建的一个新的请求
	 * 原理：将旧请求中的请求头传入新的请求头中
	 */
	@Override
	public void apply(RequestTemplate template) {
		//1. 得到原来的旧的请求对象
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		String username = request.getHeader("username");
		//2. 得到原来的cookie数组
		Cookie[] cookies = request.getCookies();
		String  c = null;
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals("c1")){
				c = cookie.getValue();
				break;
			}
		}
		//2. 将请求头中的数据取出放到新的请求头中

		template.header("username",username);
		// template.header("c1",c);
	}
}
